package com.example.security.realm;

import com.example.core.utils.Sha256HashUtils;
import com.example.security.dto.UserAuthInfo;
import com.example.sys.org.po.SysUser;
import com.example.sys.org.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/***
 *
 * Shiro认证
 */
@Service
public class SysJWTAuthorizingRealm extends AuthorizingRealm implements ApplicationContextAware {

    public static final String SALT = "26a3bb77b691455c9cefc9bb10c9c4a6";

    private ApplicationContext applicationContext;

    private SysUserService sysUserService;

    public SysUserService getSysUserService() {
        if (sysUserService == null) {
            sysUserService = applicationContext.getBean(SysUserService.class);
        }
        return sysUserService;
    }

    /****
     * 用户授权的方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserAuthInfo userInfo = this.getSysUserService().getUserInfo();
        return new SimpleAuthorizationInfo(userInfo.getRoles());
    }


    /****
     *
     * 用户登录的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        if (StringUtils.isEmpty(userName)) {
            throw new AuthenticationException("用户名不可为空");
        }
        SysUser sysUser = this.getSysUserService().getUserByLoginName(userName);
        if (sysUser == null) {
            throw new AuthenticationException("未找到用户名: " + userName + " 对应的用户.");
        }
        String passwordInput = new String((char[]) authenticationToken.getCredentials());
        if (!Sha256HashUtils.encrypt(passwordInput, SALT).equals(sysUser.getPassWord())) {
            throw new AuthenticationException("用户名，密码错误");
        }
        return new SimpleAuthenticationInfo(sysUser,
                passwordInput, null, getName());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
